package com.qhit.controller;

import com.qhit.pojo.User;
import com.qhit.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.HashMap;
import java.util.List;

@Controller
@RequestMapping("user")
public class UserController {
    @Autowired
    private UserService userService;
    @RequestMapping("list")
    public String list(Model m,String keywords ,@RequestParam(defaultValue = "1",required = false)Integer page
            ,@RequestParam(defaultValue = "1",required = false)Integer pageSize){
        HashMap hashMap=new HashMap();
        hashMap.put("keywords",keywords);
        hashMap.put("page",page);
        hashMap.put("start",(page-1)*pageSize);
        hashMap.put("pageSize",pageSize);
        List<User> user=userService.getList(hashMap);
        long total=userService.getListCount(hashMap);
        hashMap.put("totalPage",(total%pageSize==0)?(total/pageSize):(total/pageSize+1));
        m.addAttribute("userList",user);
        m.addAttribute("myParams",hashMap);
        return "user/list";
    }
    @RequestMapping("/toAdd")
    public String toAdd(){
        return "user/add";
    }
    @RequestMapping(value = "/add",method= RequestMethod.POST)
    public String add(User user,Model m){
      int result=  userService.add(user);
      if (result>0){
          m.addAttribute("msg","添加成功");
      }else {
          m.addAttribute("msg","添加失败");
      }
      return "user/msg";
    }
    @RequestMapping("/toEdit")
    public String toEdit(String id,Model m){
        User g=userService.getUserById(id);
        m.addAttribute("user",g);
        return "user/edit";

    }
    @RequestMapping(value = "/edit",method = RequestMethod.POST)
    public String edit(User user,Model m){
       int resout=userService.edit(user);
       if (resout>0){
           m.addAttribute("msg","更新成功");
       }else {
           m.addAttribute("msg","更新失败");
       }

        return "user/msg";

    }
    @RequestMapping(value = "/del",method = RequestMethod.GET)
    public String del(String id,Model m){
        int resout=userService.del(id);
        if (resout>0){
            m.addAttribute("msg","删除成功");
        }else {
            m.addAttribute("msg","删除失败");
        }

        return "user/msg";

    }
}
